import { Injectable } from '@nestjs/common';
import { CreateDeptDto } from './dto/create-dept.dto';
import { UpdateDeptDto } from './dto/update-dept.dto';
import { QueryDeptDto } from './dto/query-dept.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Dept } from './entities/dept.entity';
import { User } from 'src/system/user/entities/user.entity';
import { Repository,Like } from 'typeorm';
import { Request } from 'express';

@Injectable()
export class DeptService {
  constructor(
    @InjectRepository(Dept) private readonly dept:Repository<Dept>
  ) {}

  /**
   * 创建部门
   * @param createDeptDto 
   * @param request 
   * @returns 
   */
  create(createDeptDto: CreateDeptDto,request: Request) {
    let user = request.user as User;
    createDeptDto.create_by = user.username;
    return this.dept.save(createDeptDto)
  }

  /**
   * 获取部门列表
   * @param query 
   * @returns 
   */
  findAll(query: QueryDeptDto) {
    let whereConditions: QueryDeptDto = {};

    if (query.dept_name) {
      whereConditions.dept_name = Like(`%${query.dept_name}%`);
    } 
    if(query.status) {
      whereConditions.status = query.status
    }
    return this.dept.find({
      where: whereConditions,
    });
  }

  /**
   * 获取部门详情
   * @param id 
   * @returns 
   */
  findOne(id: number) {
    console.log("🚀 ~ DeptService ~ findOne ~ id:", id)
    return this.dept.findOne({where:{dept_id:id}});
  }

  /**
   * 更新部门
   * @param id 
   * @param updateDeptDto 
   * @param request 
   * @returns 
   */
  update(id: number, updateDeptDto: UpdateDeptDto,request:Request) {
    let user = request.user as User;
    updateDeptDto.update_by = user.username;
    return this.dept.update(id,updateDeptDto);
  }

  /**
   * 删除部门
   * @param id 
   * @returns 
   */
  remove(id: number) {
    return this.dept.delete(id);
  }
}
